package ru.aptu.gsp_banking.dao_impl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import ru.aptu.gsp_banking.dao.CardDAO;
import ru.aptu.gsp_banking.domain.Card;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 11/18/11
 * Time: 1:27 AM
 */

@Repository
public class CardDAOImpl implements CardDAO {

    @Autowired
	private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public List<Card> listCard(Integer accountId) {
        return (List<Card>) sessionFactory.getCurrentSession().
                createQuery("from Card where account_id=" + accountId.toString()).list();
    }

    public void removeCard(Integer id) {
        Card card = (Card) sessionFactory.getCurrentSession().load(
				Card.class, id);
		if (card != null) {
			sessionFactory.getCurrentSession().delete(card);
		}
    }

    public void addCard(Card card) {
        sessionFactory.getCurrentSession().save(card);
    }

    public void updateCard(Card card) {
        sessionFactory.getCurrentSession().update(card);
    }

    public Card getCard(Integer cardId) {
        return (Card)sessionFactory.getCurrentSession().createQuery("from Card where id=" + Integer.toString(cardId)).uniqueResult();
    }

    public boolean checkCard(Integer cardId, String name) {
        Card queryResult = (Card)sessionFactory.getCurrentSession().createQuery("from Card where id=" + Integer.toString(cardId) +
                " and accountId in (select id from Account where username='" + name + "')").uniqueResult();

        return (queryResult != null);
    }

    public String getLastCardNumber() {
        Card queryResult = (Card)sessionFactory.getCurrentSession().createQuery("from Card where cardNumber=" +
                "(select max(cardNumber) from Card)").uniqueResult();

        return queryResult.getCardNumber();
    }
}
